/**
 * Created by mg123 on 2018/3/18.
 */
var contractGrid, contractStroe, contractDialog, typeData;
isAdd = false;
$(function () {
    initCombo();
    initGrid();
    initDialog();

});

function initCombo() {

    CommonClass.AjaxAction(ctx + "/contract/admin/getAllMachineTypes", {}, function (data) {
        typeData = data;
        CommonClass.setComboData($('#searchForm1 select[name=machineTypeId]'), data, "id", "name", "All");
        CommonClass.setComboData($('#contractDialogContent select[name=machineTypeId]'), data, "id", "name");

    })

}

function initGrid() {
    var Grid = BUI.Grid,
        Store = BUI.Data.Store,
        Format = Grid.Format,
        columns = [
            {title: '合约ID', dataIndex: 'id', width: 70},
            {title: '合约名称', dataIndex: 'contractName', width: 200},
            {title: '售价', dataIndex: 'price', width: 100},
            {title: '合约类型', dataIndex: 'contractType', width: 100},
            {title: '结算周期', dataIndex: 'settlementCycle', width: 100},
            {title: '合约周期', dataIndex: 'contractCycle', width: 100},
            {title: '收益发放时间', dataIndex: 'incomePaymentTime', width: 100, renderer: foramtDate},
            {title: '矿机类型', dataIndex: 'machineTypeId', width: 100, visible: false},
            {title: '矿机类型', dataIndex: 'machineTypeName', width: 100},
            {title: '算力', dataIndex: 'computingPower', width: 100},
            {title: '电费', dataIndex: 'electricityFee', width: 100},
            {title: '管理费', dataIndex: 'managementCost', width: 100},
            {title: '交割时间', dataIndex: 'deliveryTime', width: 100, renderer: foramtDate},
            {title: '上线时间', dataIndex: 'onlineTime', width: 100, renderer: foramtDate},
            {title: '总算力', dataIndex: 'total', width: 100},
            {title: '库存', dataIndex: 'stock', width: 100},
            {title: '最小购买份数', dataIndex: 'minimumNumber', width: 100},
            {title: '内容', dataIndex: 'content', width: 100, showTip: true, renderer: foramtDate},
            {title: '风险提示', dataIndex: 'riskHints', width: 100, showTip: true},
            {title: '创建时间', dataIndex: 'createTime', width: 140}
        ];

    contractStroe = new Store({
        url: ctx + "/contract/admin/selectPageInfo",
        autoLoad: true,
        root: 'list',               //存放数据的字段名(rows)
        totalProperty: 'total',
        pageSize: 10	// 配置分页数目
    });
    contractGrid = new Grid.Grid({
        render: '#contractGrid',
        columns: columns,
        width: "100%",
        store: contractStroe,
        bbar: {
            // pagingBar:表明包含分页栏
            pagingBar: true
        },
        tbar: {
            items: [{
                btnCls: 'button button-primary button-small',
                text: '新增',
                handler: addContract
            }, {
                btnCls: 'button button-primary button-small',
                text: '修改',
                handler: editContract
            }, {
                btnCls: 'button button-primary button-small',
                text: '删除',
                handler: deleteContract
            }, {
                btnCls: 'button button-primary button-small',
                text: '修改合约书',
                handler: editTip
            }]
        },
        plugins: [Grid.Plugins.CheckSelection]
    });
    contractGrid.render();
    //创建表单，表单中的日历，不需要单独初始化
    var form = Bui.formRender("searchForm1");

    form.on('beforesubmit', function (ev) {
        //序列化成对象
        var obj = form.serializeToObject();
        obj.start = 0; //返回第一页
        contractStroe.load(obj);
        return false;
    });
    contractStroe.load();


}

function initDialog() {
    userEditForm = Bui.formRender("EditForm");
    BUI.use('bui/calendar', function (Calendar) {
        var datepicker = new Calendar.DatePicker({
            trigger: '.calendar',
            autoRender: true
        });
    });

    contractDialog = Bui.overlay({
        id: 'contractDialog',
        title: '修改合约信息',
        width: 550,
        height: 350,
        //配置DOM容器的编号
        contentId: 'contractDialogContent',
        buttons: [
            {
                text: '保存',
                elCls: 'button button-primary',
                handler: function () {
                    if (!userEditForm.isValid()) {
                        return;
                    }
                    var formVal = userEditForm.serializeToObject();
                    if (isAdd) {
                        formVal.id = null;
                        formAction(formVal, ctx + "/contract/admin/insertContract");
                    } else {
                        // formVal.roleId = curResrouceId;
                        formAction(formVal, ctx + "/contract/admin/updateContract");
                    }
                }
            }, {
                text: '关闭',
                elCls: 'button',
                handler: function () {
                    this.close();
                }
            }
        ]
    });


    tipDialog = Bui.overlay({
        id: 'tipDialog',
        title: '修改合约书',
        width: 800,
        height: 450,
        //配置DOM容器的编号
        contentId: 'tipDialogContent',
        bodyContent: '<div id="editDiv" style="width: 100%;height: 100%"></div>',
        buttons: [
            {
                text: '保存',
                elCls: 'button button-primary',
                handler: function () {
                    var selections = contractGrid.getSelection();
                    var formVal = {
                        id: selections[0].id,
                        contractBook: editor.txt.html()
                    }
                    CommonClass.AjaxAction(ctx + "/contract/admin/updateContract", formVal, function (data) {
                        if (data.success) {
                            Message.show(data.msg, "success", 2000);
                            contractStroe.load()
                            tipDialog.close();
                        } else {
                            Message.show(data.msg, "error", 2000);
                        }
                    });

                }
            }, {
                text: '关闭',
                elCls: 'button',
                handler: function () {
                    this.close();
                }
            }
        ]
    });


}

function foramtDate(value, obj) {
    if (value == null || value == undefined) {
        return "";
    }
    return value.substr(0, 10);

}

function addContract() {
    isAdd = true;
    contractDialog.set("title", "新增合约信息");
    document.getElementById("EditForm").reset();
    CommonClass.fieldVaild();
    contractDialog.show();
    CommonClass.setComboData($('.machineTypeId'), typeData, "id", "name");

}

function editContract() {
    // CommonClass.setComboData($('.machineTypeId'), typeData, "id", "name");
    var selections = contractGrid.getSelection();
    isAdd = false
    if (selections.length == 0) {
        BUI.Message.Alert('请选择一条记录！', function () {
        }, 'info');
        return;
    }
    if (selections.length > 1) {
        BUI.Message.Alert('只能选择一条记录！', function () {
        }, 'info');
        return;
    }
    document.getElementById("EditForm").reset();
    CommonClass.setComboData($('#EditForm select[name=machineTypeId]'), typeData, "id", "name");
    CommonClass.setForm('EditForm', selections[0]);
    contractDialog.set("title", "修改合约信息");
    contractDialog.show();


}

function deleteContract() {
    CommonClass.deleteGridData(contractGrid, contractStroe, ctx + "/contract/admin/deleteContract");
}

function editTip() {
    var selections = contractGrid.getSelection();
    if (selections.length == 0) {
        BUI.Message.Alert('请选择一条记录！', function () {
        }, 'info');
        return;
    }
    if (selections.length > 1) {
        BUI.Message.Alert('只能选择一条记录！', function () {
        }, 'info');
        return;
    }
    tipDialog.show();
    var E = window.wangEditor
    editor = new E('#editDiv')
    editor.create()
    editor.customConfig.menus = [
        'head',  // 标题
        'bold',  // 粗体
        'fontSize',  // 字号
        'fontName',  // 字体
        'italic',  // 斜体
        'underline',  // 下划线
        'strikeThrough',  // 删除线
        'foreColor',  // 文字颜色
        'backColor',  // 背景颜色
        'link',  // 插入链接
        'list',  // 列表
        'justify',  // 对齐方式
        'quote',  // 引用
        'emoticon',  // 表情
        'undo',  // 撤销
        'redo'  // 重复
    ]

    editor.txt.html(selections[0].contractBook)
}

function formAction(formVal, actionUrl) {
    CommonClass.AjaxAction(actionUrl, formVal, function (data) {
        if (data.success) {
            Message.show(data.msg, "success", 2000);
            contractStroe.load()
            contractDialog.close();
        } else {
            Message.show(data.msg, "error", 2000);
        }
    });
}